package handler

import (
	"hrms-api/model"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

// DepartmentRequest 部门请求结构
type DepartmentRequest struct {
	Name        string `json:"name" binding:"required,max=50"`
	Description string `json:"description" binding:"max=500"`
	ManagerID   uint   `json:"manager_id" binding:"required"`
	ParentID    uint   `json:"parent_id"`
	Level       int    `json:"level" binding:"required"`
	Status      int    `json:"status" binding:"oneof=0 1"`
}

// CreateDepartment 创建部门
func CreateDepartment(c *gin.Context) {
	var req DepartmentRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		BadRequest(c, "Invalid request parameters")
		return
	}

	// 检查部门名称是否已存在
	var existingDept model.Department
	result := model.DB.Where("name = ?", req.Name).First(&existingDept)
	if result.Error != gorm.ErrRecordNotFound {
		BadRequest(c, "Department name already exists")
		return
	}

	// 检查管理者是否存在
	var manager model.User
	if err := model.DB.First(&manager, req.ManagerID).Error; err != nil {
		BadRequest(c, "Manager not found")
		return
	}

	// 如果有父部门，检查父部门是否存在
	if req.ParentID != 0 {
		var parentDept model.Department
		if err := model.DB.First(&parentDept, req.ParentID).Error; err != nil {
			BadRequest(c, "Parent department not found")
			return
		}
	}

	dept := model.Department{
		Name:        req.Name,
		Description: req.Description,
		ManagerID:   req.ManagerID,
		ParentID:    req.ParentID,
		Level:       req.Level,
		Status:      req.Status,
	}

	if err := model.DB.Create(&dept).Error; err != nil {
		InternalServerError(c, "Failed to create department")
		return
	}

	Success(c, dept)
}

// GetDepartment 获取部门信息
func GetDepartment(c *gin.Context) {
	deptID := c.Param("id")

	var dept model.Department
	result := model.DB.Preload("Manager").Preload("Parent").First(&dept, deptID)
	if result.Error != nil {
		NotFound(c, "Department not found")
		return
	}

	Success(c, dept)
}

// UpdateDepartment 更新部门信息
func UpdateDepartment(c *gin.Context) {
	deptID := c.Param("id")

	var req DepartmentRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		BadRequest(c, "Invalid request parameters")
		return
	}

	var dept model.Department
	if err := model.DB.First(&dept, deptID).Error; err != nil {
		NotFound(c, "Department not found")
		return
	}

	// 检查部门名称是否与其他部门重复
	if req.Name != dept.Name {
		var existingDept model.Department
		result := model.DB.Where("name = ? AND id != ?", req.Name, deptID).First(&existingDept)
		if result.Error != gorm.ErrRecordNotFound {
			BadRequest(c, "Department name already exists")
			return
		}
	}

	// 检查管理者是否存在
	var manager model.User
	if err := model.DB.First(&manager, req.ManagerID).Error; err != nil {
		BadRequest(c, "Manager not found")
		return
	}

	// 如果有父部门，检查父部门是否存在
	if req.ParentID != 0 {
		var parentDept model.Department
		if err := model.DB.First(&parentDept, req.ParentID).Error; err != nil {
			BadRequest(c, "Parent department not found")
			return
		}
	}

	// 更新部门信息
	updates := map[string]interface{}{
		"name":        req.Name,
		"description": req.Description,
		"manager_id":  req.ManagerID,
		"parent_id":   req.ParentID,
		"level":       req.Level,
		"status":      req.Status,
	}

	if err := model.DB.Model(&dept).Updates(updates).Error; err != nil {
		InternalServerError(c, "Failed to update department")
		return
	}

	Success(c, dept)
}

// DeleteDepartment 删除部门
func DeleteDepartment(c *gin.Context) {
	deptID := c.Param("id")

	// 检查是否有子部门
	var childDepts []model.Department
	if err := model.DB.Where("parent_id = ?", deptID).Find(&childDepts).Error; err != nil {
		InternalServerError(c, "Failed to check child departments")
		return
	}

	if len(childDepts) > 0 {
		BadRequest(c, "Cannot delete department with child departments")
		return
	}

	// 删除部门
	if err := model.DB.Delete(&model.Department{}, deptID).Error; err != nil {
		InternalServerError(c, "Failed to delete department")
		return
	}

	Success(c, gin.H{"message": "Department deleted successfully"})
}

// GetDepartments 获取部门列表
func GetDepartments(c *gin.Context) {
	// 获取查询参数
	status := c.Query("status")

	// 构建查询条件
	query := model.DB.Preload("Manager").Preload("Parent")
	if status != "" {
		query = query.Where("status = ?", status)
	}

	// 查询部门列表
	var depts []model.Department
	if err := query.Find(&depts).Error; err != nil {
		InternalServerError(c, "Failed to get departments")
		return
	}

	Success(c, depts)
}
